package com.gewu.advertisement.core

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Parcel
import android.os.Parcelable
import android.view.WindowManager
import com.gewu.advertisement.core.model.Advertising
import com.gewu.advertisement.core.model.Advertising.TextRollDirection.LEFT_TO_RIGHT
import com.gewu.advertisement.core.model.Advertising.TextRollDirection.RIGHT_TO_LEFT

/**
 * @author htt 2020/10/23
 */
@SuppressLint("ViewConstructor")
class AdvertisementTextView(
    context: Context,
    val advertising: Advertising
) : android.support.v7.widget.AppCompatTextView(context) {

    private var textLength = 0f //文本长度
    private var viewWidth = 0f
    private var textX = 0f //文字的横坐标
    private var textY = 0f //文字的纵坐标
    private var isStarting = false //是否开始滚动
    private var paint: Paint? = null //绘图样式
    var actualText = ""

    var scrollSpeed = 12 //文字滚动速度
    var direction = RIGHT_TO_LEFT //文字滚动方向

    var isShow = false   //是否显示

    /**
     * Activity中使用方法：
     * //启动公告滚动条
     * autoScrollTextView = (AutoScrollTextView)findViewById(R.id.TextViewNotice);
     * autoScrollTextView.init(getWindowManager());
     * autoScrollTextView.startScroll();
     * 注：如果想改变跑马灯的文字内容或者文字效果，则在调用完setText方法之后，需要再调用一下init方法，重新进行初始化和相关参数的计算。
     */
    fun init(windowManager: WindowManager?) {
        paint = getPaint()
        paint!!.textSize = textSize
        textLength = paint!!.measureText(actualText)
        viewWidth = width.toFloat()
        if (viewWidth == 0f) {
            if (windowManager != null) {
                val display = windowManager.defaultDisplay
                viewWidth = display.width.toFloat()
            }
        }
        //TODO 设置字体颜色
        textX = when(direction) {
            LEFT_TO_RIGHT -> 0f
            RIGHT_TO_LEFT -> viewWidth
        }
        textY = textSize + paddingTop
    }

    override fun onSaveInstanceState(): Parcelable {
        val superState: Parcelable = super.onSaveInstanceState()!!
        val ss = SavedState(superState)
        ss.step = textX
        ss.isStarting = isStarting
        return ss
    }

    override fun onRestoreInstanceState(state: Parcelable?) {
        if (state !is SavedState) {
            super.onRestoreInstanceState(state)
            return
        }
        super.onRestoreInstanceState(state.superState)
        textX = state.step
        isStarting = state.isStarting
    }

    class SavedState : BaseSavedState {
        var isStarting = false
        var step = 0.0f

        internal constructor(superState: Parcelable?) : super(superState) {}

        override fun writeToParcel(out: Parcel, flags: Int) {
            super.writeToParcel(out, flags)
            out.writeBooleanArray(booleanArrayOf(isStarting))
            out.writeByte((if (isStarting) 1 else 0).toByte())
            out.writeFloat(step)
        }

        private constructor(`in`: Parcel) : super(`in`) {
            val b = `in`.readByte()
            isStarting = b.toInt() == 1
            step = `in`.readFloat()
        }

        companion object {
            @JvmField val CREATOR: Parcelable.Creator<SavedState?> =
                object : Parcelable.Creator<SavedState?> {
                    override fun newArray(size: Int): Array<SavedState?> {
                        return arrayOfNulls(size)
                    }

                    override fun createFromParcel(`in`: Parcel): SavedState? {
                        return SavedState(`in`)
                    }
                }
        }
    }

    fun startScroll() {
        isStarting = true
        invalidate()
    }

    fun stopScroll() {
        isStarting = false
        invalidate()
    }

    fun isScroll(): Boolean{
        return isStarting;
    }

    override fun onDraw(canvas: Canvas) {
        if (paint == null) {
            super.onDraw(canvas)
            return
        }
        paint!!.color = currentTextColor
        // view宽度 + text宽度 - textX
        canvas.drawText(actualText, textX, textY, paint!!)
        if (!isStarting) {
            return
        }
        var step = 1.5f + (scrollSpeed - 12) * 0.1f  //文字滚动距离
        if (step <= 1.0) step = 1.1f                 //最小滚动距离
        when (direction) {
            LEFT_TO_RIGHT -> {
                textX += step
                if (textX > viewWidth) textX = 0f - textLength
            }
            RIGHT_TO_LEFT -> {
                textX -= step
                if (textX < 0 - textLength) textX = viewWidth
            }
        }
        invalidate()
    }
}